import os

from dotenv import load_dotenv
from langchain_openai import AzureChatOpenAI
from langgraph.graph import StateGraph, END
from typing import TypedDict, Annotated, List, Dict
import operator
from datetime import datetime
import json

load_dotenv()
llm = AzureChatOpenAI(
    api_key=os.getenv("AZURE_OPENAI_API_KEY"),
    azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
    azure_deployment=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
    api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
    temperature=0.8
)


class DebateState(TypedDict):
    """辩论状态定义"""
    topic: str
    participants: List[str]
    positions: Dict[str, str]
    debate_round: int
    max_rounds: int
    messages: Annotated[List[Dict], operator.add]
    consensus_reached: bool
    consensus_summary: str
    participant_scores: Dict[str, int]  # 记录参与者表现分数


def create_debate_agent(role: str, position: str, expertise: str):
    """创建具有专业背景的辩论Agent"""

    def debate_node(state: DebateState):
        print(f"\n🎤 [{role}] 正在发言...")

        # 获取辩论上下文
        topic = state["topic"]
        messages = state["messages"]
        current_round = state["debate_round"]
        participants = state["participants"]

        # 构建最近发言历史（避免上下文过长）
        recent_debate = "\n".join([
            f"{msg['role']}: {msg['content']}"
            for msg in messages[-6:]  # 只保留最近6条消息
        ])

        prompt = f"""
# 辩论角色设定
你是一名{role}，你的专业领域是：{expertise}
你的核心立场：{position}

# 辩论背景
辩论主题：{topic}
当前回合：第{current_round}轮
参与方：{', '.join(participants)}

# 近期辩论记录
{recent_debate}

# 你的任务
请基于你的专业背景和立场，进行本轮发言：

## 发言要求
1. **论点推进**：提出新的证据或角度支持你的立场
2. **反驳回应**：针对其他参与者的观点进行有力回应
3. **共识探索**：尝试寻找共同点或建设性妥协方案
4. **专业深度**：运用你的专业知识{expertise}增强说服力

## 发言策略
- 保持专业和建设性态度
- 使用具体数据和逻辑推理
- 避免重复之前已提出的观点
- 如果认为共识已近，可主动提出总结方案

请输出你的发言内容：
"""
        response = llm.invoke([{"role": "user", "content": prompt}])

        # 分析发言质量（简单评分）
        content = response.content
        score_factors = {
            "专业术语": len([w for w in content.split() if len(w) > 8]),
            "逻辑连接词": len([w for w in ["因为", "所以", "然而", "因此", "尽管"] if w in content]),
            "数据引用": any(char.isdigit() for char in content)
        }
        score = sum(score_factors.values())

        return {
            "messages": [{
                "role": role,
                "content": content,
                "timestamp": datetime.now().isoformat(),
                "round": current_round
            }],
            "participant_scores": {
                **state["participant_scores"],
                role: state["participant_scores"].get(role, 0) + score
            }
        }

    return debate_node


def moderator_node(state: DebateState):
    """主持人Agent：协调辩论并评估共识进展"""
    print(f"\n🎯 [主持人] 正在评估第{state['debate_round']}轮辩论...")

    messages = state["messages"]
    current_round = state["debate_round"]
    max_rounds = state["max_rounds"]

    # 分析辩论内容
    debate_text = "\n".join([f"{msg['role']}: {msg['content']}" for msg in messages])

    prompt = """
# 主持人评估任务
你是一名专业的辩论主持人，需要评估当前辩论状态。

## 辩论信息
主题：{state['topic']}
当前轮次：{current_轮}/{max_rounds}
参与方：{', '.join(state['participants'])}

## 完整辩论记录
{debate_text}

## 评估要求
请从以下维度进行评估：

### 1. 共识程度分析
- 各方立场是否在接近？
- 是否出现了建设性的妥协方案？
- 主要分歧点是否在缩小？

### 2. 辩论质量评估  
- 各方论点是否有理有据？
- 是否出现了新的见解或解决方案？
- 辩论是否陷入僵局或重复？

### 3. 进程决策
基于以上分析，请决定：
- 继续辩论（如果还有进展空间且未达轮次限制）
- 结束辩论并总结共识（如果已达成有意义共识）
- 结束辩论并说明分歧（如果陷入僵局）

请按以下JSON格式输出：
{{
    "decision": "continue|consensus|deadlock",
    "reason": "详细的分析理由",
    "consensus_summary": "如果达成共识的总结，否则为空",
    "key_insights": ["主要见解1", "主要见解2"]
}}
"""
    response = llm.invoke([{"role": "user", "content": prompt}])

    try:
        analysis = json.loads(response.content)
    except:
        # 如果JSON解析失败，使用文本分析
        analysis = {
            "decision": "continue" if current_round < max_rounds else "deadlock",
            "reason": "自动分析",
            "consensus_summary": "",
            "key_insights": []
        }

    consensus_reached = analysis["decision"] != "continue"

    return {
        "debate_round": current_round + 1,
        "consensus_reached": consensus_reached,
        "consensus_summary": analysis["consensus_summary"],
        "messages": [{
            "role": "主持人",
            "content": f"第{current_round}轮评估：{analysis['reason']}",
            "decision": analysis["decision"]
        }]
    }


def create_enhanced_debate_workflow():
    """创建增强版辩论工作流"""
    workflow = StateGraph(DebateState)

    # 定义辩论参与者及其专业背景
    participants_config = {
        "技术专家": {
            "position": "应该优先采用最先进的技术方案确保系统长期竞争力",
            "expertise": "技术架构、系统性能、可扩展性"
        },
        "产品经理": {
            "position": "应该优先考虑用户需求和产品体验，技术服务于业务",
            "expertise": "用户研究、市场需求、产品设计"
        },
        "商业分析师": {
            "position": "应该优先考虑商业价值和投资回报率",
            "expertise": "商业模式、财务分析、市场趋势"
        }
    }

    # 添加辩论者节点
    for role, config in participants_config.items():
        workflow.add_node(
            role,
            create_debate_agent(role, config["position"], config["expertise"])
        )

    workflow.add_node("moderator", moderator_node)

    # 设置入口点
    workflow.set_entry_point("技术专家")

    # 定义动态辩论流程
    def get_next_speaker(state):
        """动态选择下一个发言者"""
        messages = state["messages"]
        if not messages:
            return "技术专家"

        # 简单的轮换机制
        last_speaker = messages[-1]["role"] if messages else ""
        participants = state["participants"]

        if last_speaker in participants:
            current_index = participants.index(last_speaker)
            next_index = (current_index + 1) % len(participants)
            return participants[next_index]
        else:
            return participants[0]

    # 添加条件边缘
    for role in participants_config.keys():
        workflow.add_edge(role, "moderator")

    # 主持人后的条件流转
    def should_continue(state):
        if state["consensus_reached"]:
            return "final_summary"
        elif state["debate_round"] >= state["max_rounds"]:
            return "final_summary"
        else:
            return get_next_speaker(state)

    workflow.add_conditional_edges("moderator", should_continue)

    # 最终总结节点
    def final_summary_node(state):
        """生成最终辩论总结"""
        print("\n📊 [系统] 生成最终总结...")

        messages = state["messages"]
        scores = state["participant_scores"]

        # 生成辩论总结
        debate_content = "\n".join([f"{msg['role']}: {msg['content']}" for msg in messages])

        prompt = f"""
基于以下辩论记录生成全面总结：

辩论主题：{state['topic']}
总轮次：{state['debate_round']}
参与者得分：{scores}

辩论内容：
{debate_content}

请生成包含以下内容的总结报告：
1. 主要共识点
2. 核心分歧点  
3. 各方关键论点
4. 达成的结论或建议
5. 参与者表现评价

要求：专业、客观、结构化
"""

        response = llm.invoke([{"role": "user", "content": prompt}])

        return {
            "consensus_summary": response.content,
            "messages": [{
                "role": "系统",
                "content": f"辩论结束！最终报告：{response.content}"
            }]
        }

    workflow.add_node("final_summary", final_summary_node)
    workflow.add_edge("final_summary", END)

    return workflow.compile()


def run_enhanced_debate():
    """运行增强版辩论系统"""
    debate_app = create_enhanced_debate_workflow()

    initial_state = {
        "topic": "在开发新一代AI产品时，应该优先投入资源在技术突破还是用户体验优化？",
        "participants": ["技术专家", "产品经理", "商业分析师"],
        "positions": {},
        "debate_round": 1,
        "max_rounds": 4,  # 最大辩论轮次
        "consensus_reached": False,
        "consensus_summary": "",
        "participant_scores": {},
        "messages": [{
            "role": "系统",
            "content": f"辩论开始！主题：在开发新一代AI产品时，应该优先投入资源在技术突破还是用户体验优化？"
        }]
    }

    print("🎭 启动增强版多Agent辩论系统...")
    print(f"辩论主题: {initial_state['topic']}")
    print(f"参与方: {', '.join(initial_state['participants'])}")
    print(f"最大轮次: {initial_state['max_rounds']}")
    print("=" * 60)

    # 执行辩论工作流
    result = debate_app.invoke(initial_state)

    # 输出结果
    print("\n" + "=" * 60)
    print("🏁 辩论系统执行完成!")
    print("=" * 60)
    print(f"总执行轮次: {result['debate_round'] - 1}")
    print(f"参与者得分: {result['participant_scores']}")
    print("\n📋 最终总结报告:")
    print("=" * 60)
    print(result['consensus_summary'])

    # 输出辩论记录
    print("\n" + "=" * 60)
    print("🗣️ 完整辩论记录:")
    print("=" * 60)
    for msg in result['messages']:
        if msg['role'] != '系统':  # 过滤系统消息
            print(f"\n[{msg['role']}] {msg['content']}")

    return result

""" [可选]将reslut结果，保存到一个markdown文件中"""
def generate_beautiful_markdown(result):
    """生成更精美的Markdown报告"""

    topic = result.get('topic', '未知主题')
    total_rounds = result.get('debate_round', 1) - 1
    consensus_reached = result.get('consensus_reached', False)
    participant_scores = result.get('participant_scores', {})
    consensus_summary = result.get('consensus_summary', '')
    messages = result.get('messages', [])

    content = [
        "# 🎭 多智能体辩论系统分析报告\n",
        "---",
        "",
        "## 📋 执行概览",
        "",
        "| 项目 | 结果 |",
        "|------|------|",
        f"| 🎯 **辩论主题** | {topic} |",
        f"| ⏱️ **总辩论轮次** | {total_rounds} |",
        f"| 🤝 **共识状态** | {'✅ 已达成共识' if consensus_reached else '🔄 未达成共识'} |",
        f"| 📅 **生成时间** | {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} |",
        "",
        "---",
        "",
        "## 🏆 参与者表现排行榜",
        ""
    ]

    # 参与者评分表格
    if participant_scores:
        content.append("| 排名 | 参与者 | 得分 | 表现评价 |")
        content.append("|------|--------|------|----------|")

        sorted_scores = sorted(participant_scores.items(), key=lambda x: x[1], reverse=True)
        for i, (participant, score) in enumerate(sorted_scores, 1):
            performance = "🌟 优秀" if score > 20 else "✅ 良好" if score > 10 else "📊 一般"
            medal = "🥇" if i == 1 else "🥈" if i == 2 else "🥉" if i == 3 else "📝"
            content.append(f"| {medal} {i} | **{participant}** | `{score}分` | {performance} |")

    content.extend([
        "",
        "---",
        "",
        "## 📊 最终共识总结",
        "",
        "```",
        consensus_summary if consensus_summary else "本次辩论未达成明确共识",
        "```",
        "",
        "---",
        "",
        "## 🗣️ 辩论过程记录",
        ""
    ])

    # 辩论过程记录
    current_round = 0
    for msg in messages:
        if msg.get('round', 0) != current_round:
            current_round = msg.get('round', 0)
            content.append(f"### 🔄 第{current_round}轮辩论")
            content.append("")

        role = msg.get('role', '未知角色')
        message_content = msg.get('content', '')

        if role == "主持人":
            content.append(f"#### 🎯 {role}")
            content.append(f"📢 **评估意见**: {message_content}")
        elif role == "系统":
            content.append(f"#### ⚡ {role}")
            content.append(f"🔔 {message_content}")
        else:
            content.append(f"#### 👤 {role}")
            content.append(f"{message_content}")

        content.append("")

    content.extend([
        "---",
        "",
        "## 📈 数据统计",
        "",
        "### 基础统计",
        ""
    ])

    # 基础统计
    total_messages = len(messages)
    participant_messages = len([m for m in messages if m.get('role') not in ['主持人', '系统']])

    content.extend([
        f"- **总消息数量**: {total_messages} 条",
        f"- **参与者发言**: {participant_messages} 次",
        f"- **主持人干预**: {total_messages - participant_messages} 次",
        f"- **参与者数量**: {len(participant_scores)} 位",
        "",
        "### 表现分析",
        ""
    ])

    if participant_scores:
        max_score = max(participant_scores.values())
        min_score = min(participant_scores.values())
        avg_score = sum(participant_scores.values()) / len(participant_scores)

        content.extend([
            f"- **最高得分**: {max_score} 分",
            f"- **最低得分**: {min_score} 分",
            f"- **平均得分**: {avg_score:.1f} 分",
            f"- **得分差距**: {max_score - min_score} 分",
        ])

    content.extend([
        "",
        "---",
        "",
        "## 💡 系统评价",
        "",
        "> 本辩论由多智能体系统自动执行，展现了AI在复杂决策和协商中的潜力。",
        "",
        "**技术架构**: LangGraph + 多智能体协作 + 动态评估机制",
        "",
        "*报告生成时间: {}*".format(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    ])

    return "\n".join(content)


# 使用精美版本保存
def save_beautiful_report(result):
    """保存精美版报告"""
    beautiful_content = generate_beautiful_markdown(result)
    filename = f"debate_beautiful_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"

    with open(filename, 'w', encoding='utf-8') as f:
        f.write(beautiful_content)

    print(f"🎨 精美报告已保存: {filename}")
    return filename


if __name__ == "__main__":
    result = run_enhanced_debate()
    ## 保存文件
    save_beautiful_report(result)
